<?php

namespace App\Console\Commands;

use App\Models\Base\ServerList;
use App\Models\Base\StatHourOrder;
use App\Service\OrderService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class FetchHourOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fetch:hourOrder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '每个时间段的订单统计';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $carbon_now = Carbon::now();
        $hour = $carbon_now->format('H');
        $date_time = $carbon_now->toDateString();

        if ('00' == $hour) {
            $hour = 23;
            $date_time = Carbon::yesterday()->toDateString();
        }

        $serverIds = ServerList::pluck('server_id');
        if ($serverIds->isEmpty()) {
            Log::error('统计时段订单数据,游戏服不存在');

            return false;
        }
        $now_hour = $carbon_now->timestamp;
        $one_hour_ago = $carbon_now->subHours(1)->timestamp;
        foreach ($serverIds as $server_id) {
            $data['date_time'] = $date_time;
            $data['server_id'] = $server_id;
            $data['hour'] = $hour;
            //订单金额
            $data['amount'] = OrderService::getDayOrderAmount($one_hour_ago, $now_hour, $server_id);
            $data['order_number'] = OrderService::getTodayOrderNum($one_hour_ago, $now_hour, $server_id);
            $data['pay_people_number'] = OrderService::payPlayerNum($one_hour_ago, $now_hour, $server_id);
            if (StatHourOrder::create($data)) {
                echo 'success';
            } else {
                Log::error('统计时段订单数据失败', $data);
            }
        }
    }
}
